package com.witmore.skyline.web.utils.mapworld;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;

@Slf4j
public class MapWorldGeocoder {

    public static void main(String[] args) throws IOException, InterruptedException {
        GeocodeResponse response = geocodeHandle("北京市东城区东华门街道南池子大街122号");
        System.out.println(JSONObject.toJSONString( response));

    }
    public static GeocodeResponse geocodeHandle(String address) throws IOException, InterruptedException {
        String keyWord = String.format("{\"keyWord\":\"%s\"}", address);
        String encodedDsStr = URLEncoder.encode(keyWord, StandardCharsets.UTF_8);

        // 2. 构建GET请求URL
        String url = String.format("%s?ds=%s&tk=%s",
                MapWorldConstant.MAP_WORLD_API_URL,
                encodedDsStr,
                MapWorldConstant.API_KEY);


        // 3. 创建HTTP客户端
        HttpClient httpClient = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();

        // 4. 构建GET请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .GET()  // 关键修改点
                .header("Accept", "application/json")
                .build();

        // 5. 发送请求
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

        // 6. 处理响应
        if (response.statusCode() == 200) {
            // 解析JSON响应
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(response.body(), GeocodeResponse.class);
        } else {
            throw new IOException("地理编码失败，状态码: " + response.statusCode() +
                    " 响应: " + response.body());
        }
    }

    public static Map<String, Double> geocode(String address) throws IOException, InterruptedException {
        GeocodeResponse response = geocodeHandle(address);
        if ("0".equals(response.getStatus())) {
            Location location = response.getLocation();
            return Map.of("lng", location.getLon(), "lat", location.getLat());
        } else {
            throw new IOException("Geocoding failed: " + response.getMsg());
        }
    }


    @Setter
    @Getter
    public static class GeocodeResponse {
        private String status;
        private String msg;
        private Location location;
        @JsonProperty("searchVersion")
        private String searchVersion;

        @Override
        public String toString() {
            return "GeocodeResponse{" +
                    "status='" + status + '\'' +
                    ", msg='" + msg + '\'' +
                    ", location=" + location +
                    ", searchVersion='" + searchVersion + '\'' +
                    '}';
        }
    }

    @Setter
    @Getter
    public static class Location {
        private int score;
        private String level;
        private double lon;
        private double lat;
        @JsonProperty("keyWord")
        private String keyword;

        @Override
        public String toString() {
            return "Location{" +
                    "score=" + score +
                    ", level='" + level + '\'' +
                    ", lon=" + lon +
                    ", lat=" + lat +
                    ", keyword='" + keyword + '\'' +
                    '}';
        }
    }
}
